// miniprogram/pages/home/home.js
import citys from '../../common/citys';
import Ajax from '../../common/Ajax';

const app = getApp();

Page({

    /**
     * 页面的初始数据
     */
    data: {
        show: false,
        columns: ['杭州', '宁波', '温州', '嘉兴', '湖州'],
        actions: [
            {
                text: '广交会展',
            },
            {
                text: '家具家居',
            },
            {
                text: '建筑建材',
            },
            {
                text: '化工涂料',
            },
            {
                text: '音响影视',
            },
            {
                text: '光电照明',
            },
            {
                text: '机械设备',
            },
            {
                text: '电子家电',
            },
        ],
        type: "请选择会展类型",
        location: "请选择参展地点",
        make: "请选择制作地点",
        priceRange: "请选择报价区间",
        areaList: citys,
        locationShow: false,
        makeShow: false,
        rangeShow: false,
        user: {},
        marketList: [],
        pageNo: 1,
        pageSize: 10,
        isBorder: false,
        value: "",
    },

    onShow() {
        this.getUserInfo();
    },
    /**
     * 校验是否授权
     * 
    */
    getUserInfo: function() {
        // 获取用户信息
        const sessionId = wx.getStorageSync('sessionId') || "";
        if(sessionId !== "") {
            wx.showLoading({
                title: '登录中...',
            })
            wx.getSetting({
                success: res => {
                    if (res.authSetting['scope.userInfo']) {
                        // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                        wx.getUserInfo({
                            success: res => {
                                this.setData({
                                    user: res
                                })
                                this.getMarketList({pageNo: 1, pageSize: 10})
                                // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                                // 所以此处加入 callback 以防止这种情况
                                if (this.userInfoReadyCallback) {
                                    this.userInfoReadyCallback(res)
                                }
                            }
                        })
                    } else {
                        wx.navigateTo({
                            url: '../index/index',
                        })
                    }
                }
            })
        } else {
            wx.navigateTo({
                url: '../index/index',
            })
        }
    },

    /**
     * 获取行情列表
    */
    getMarketList: function({pageNo, pageSize, designCompanyName, sign}) {
        let sessionId = wx.getStorageSync('sessionId');
        wx.showLoading({
          title: '查询中...',
        })
        Ajax.post("/designCompany/findDesignCompanyList", {
            pageNo,
            pageSize,
            designCompanyName,
        }, sessionId)
            .then(res => {
                if(res.code === "701012") {
                    this.toLogin()
                } else if(res.code === "0") {
                    let result = [];
                    if(sign === 1) {
                        result = res.data;
                    } else {
                        const {marketList} = this.data;
                        result = marketList.concat(res.data);
                    }
                    
                    this.setData({marketList: result, pageNo, pageSize}, () => {
                        if(res.data.length < 10) {
                            this.setData({isBorder: true})
                        }
                    })
                } else {
                    wx.showToast({
                      title: res.message,
                    })
                }
            })
            .catch(err => {
                throw err;
            })
            .finally(() => {
                wx.hideLoading()
            })
    },

     /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        let {pageNo, pageSize, value} = this.data;
        pageNo = pageNo + 1;
        this.getMarketList({pageNo, pageSize, designCompanyName: value});
    },

    toLogin: function() {
        wx.request({
            url: 'http://192.168.0.103:28089/wxUsers/login',
            method: "post",
            data: {
                code: app.globalData.code,
                iv: this.data.user.iv,
                encryptedData: this.data.user.encryptedData
            },
            success: res => {
                res = res.data;
                if(res.code === "0") {
                    wx.setStorageSync('sessionId', res.data.sessionId);
                    this.getMarketList()
                } else {
                    wx.showToast({
                        title: res.message,
                    })
                }
            },
            fail: err => {
               throw err;
            }
        })
    },

    toSearch: function() {
        const { value: designCompanyName } = this.data;
        this.getMarketList({pageNo: 1, pageSize: 10, designCompanyName, sign: 1})
    },

    handleChange: function(e) {
        this.setData({
            value: e.detail
        })
    },
    // onPullDownRefresh: function() {
    //     this.getMarketList({pageNo: 1, pageSize: 10})
    // },
    /**
     * 
     * 弹窗层关闭
    */
    onClose: function() {
        this.setData({show: false})
    },
    /**
     * 
     * 弹出会展类型弹出层
    */
    onChange: function() {
        this.setData({
            show: true
        })
    },
    /**
     * 改变会展类型
     * 
    */
    actionSelect: function(e) {
        this.setData({
            type: e.detail.value.text,
            show: false
        })
    },
    /**
     * 
     * 跳转查询结果页面
    */
    // toSearch: function() {
    //     wx.navigateTo({
    //         url: '../searchResult/searchResult',
    //     })
    // },
    chooseLocation: function() {
        this.setData({locationShow: true})
    },
    /**
     * 
     * 设置参展地点
    */
    setLocation: function(e) {
        const result = this.joinLoca(e);
        this.setData({
            location: result,
            locationShow: false,
        })
    },
    onCancel: function() {
        this.setData({
            show: false,
            locationShow: false,
        })
    },
    chooseMake: function() {
        this.setData({
            makeShow: true,
        })
    },
    /**
     * 
     * 拼接地点函数
    */
    joinLoca: function(e) {
        let completeName = "";
        let param = e.detail.values;
        param.forEach(item => {
            completeName += `${item.name} `
        })
        return completeName;
    },
    setMake: function(e) {
        const result = this.joinLoca(e);
        this.setData({
            make: result,
            makeShow: false,
        })
    }
})